// 动态权限路由
import asyncRoutes from '@/router/asyncRoutes'
import pageRoutes from '@/router/pageRoutes'
export const SET_ROUTERS = 'SET_ROUTERS'
export const GENERATE_ROUTES = 'GENERATE_ROUTES'

// 是否开启权限控制
const openAuthControll = true
/**
 * 判断路由是否加载
 * @param menus
 * @param route
 */
function hasPermission (permissionResources, route) {
  if (route.meta && route.meta.auth && openAuthControll) {
    return permissionResources.includes(route.meta.auth)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合员工角色权限的路由表
 * @param asyncRouterMap
 * @param menus
 */
function filterAsyncRouter (asyncRouterMap, permissionResources) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (hasPermission(permissionResources, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, permissionResources)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: pageRoutes, // 页面管理
    addRouters: [] // 动态路由级
  },
  mutations: {
    [SET_ROUTERS]: (state, routers) => {
      state.addRouters = routers
      state.routers = pageRoutes.concat(routers)
    }
  },
  actions: {
    [GENERATE_ROUTES] ({
      commit
    }, permissionResources) {
      return new Promise(resolve => {
        const accessedRouters = filterAsyncRouter(asyncRoutes, permissionResources)
        commit(SET_ROUTERS, accessedRouters)
        resolve(accessedRouters)
      })
    }
  }
}

export default permission
